package com.zbkj.front.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.enums.OrderStatusEnum;
import com.zbkj.common.model.order.OrderInfo;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.front.service.OrderHandleService;
import com.zbkj.service.service.SystemConfigService;
import com.zbkj.service.service.order.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Auther:
 * @Date: 2024/9/16 11:35
 * @Description:
 */
@Slf4j
@Component
public class OrderJobTask {
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private OrderHandleService orderHandleService;

    @XxlJob("automOrderCancelTask")
    public ReturnT<String> automOrderCancelTask() {
        String expireSecStr = systemConfigService.getValueByKey(Constants.AUTOM_ORDER_CANCEL_EXPIRED_CFG);
        int expireSec = 2*24*60*60;
        if(StringUtils.isNotBlank(expireSecStr)) {
            expireSec = Integer.valueOf(expireSecStr);
        }
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper();
        wrapper.select(OrderInfo::getId);
        wrapper.eq(OrderInfo::getDeleteFlag, 0)
                .eq(OrderInfo::getOrderStatus, OrderStatusEnum.ORDER_STATUS1.getStatus())
                .le(OrderInfo::getCreateTime, DateUtil.addSecond(new Date(),expireSec*-1))
                .last(" limit 1000");
        List<OrderInfo> taskList = orderInfoService.list(wrapper);
        for(OrderInfo orderInfo : taskList) {
            try {
                orderHandleService.automCancel(orderInfo.getId());
            } catch (Exception e) {
                log.error("automOrderCancel-orderId:{}-自动取消异常:{}",orderInfo.getId(),e.getMessage());
            }
        }
        log.info("automOrderCancelTask-orderSize:{}-end",taskList.size());
        return ReturnT.SUCCESS;
    }
}
